package com.xcc.core.netty.client;




import com.xcc.core.netty.NettyClient;
import com.xcc.core.netty.manager.ManagerChannel;
import com.xcc.core.util.ZkClientUitl;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;

public class ClientHandler extends ChannelInboundHandlerAdapter{

    ClientUtil mClientUtil=new ClientUtil();

    //创建管理通道
    @Override
    public void channelActive(ChannelHandlerContext ctx)
        throws Exception {
        String s="asdadssssssssssssssssssss";
        ByteBuf message=Unpooled.buffer(s.length());
        message.writeBytes(s.getBytes());
        ctx.writeAndFlush(message);
        ManagerChannel.putSeverChannel(ctx.channel());
      //  ZkClientUitl.createEphemeral("/server/"+ctx.channel().id().asLongText(),"".getBytes());
    }

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg)
        throws Exception {
        //    ctx.writeAndFlush(msg);

        for(String key:ManagerChannel.getAllServer().keySet()) {
            if(!key.equals(ctx.channel().id().asLongText())) {
                mClientUtil.writeClient(key,(ByteBuf)msg );
            }
        }

    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx,
                                Throwable cause)
                                    throws Exception {
        System.out.println("服务器连接异常");
        ManagerChannel.removeServer(ctx.channel());
        new NettyClient("127.0.0.1",10087).start();
        super.exceptionCaught(ctx, cause);
    }


}